import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lottie/lottie.dart';
import 'package:spring_fairy/api/mood_track_api.dart';
import 'package:spring_fairy/model/mood_point_image.dart';
import 'package:spring_fairy/model/mood_track.dart';
import 'package:spring_fairy/model/mood_type.dart';
import 'package:spring_fairy/model/store.dart';
import 'package:spring_fairy/util/notify.dart';
import 'package:spring_fairy/util/upload_images.dart';
import 'package:spring_fairy/widget/mood_widget.dart';
import '../model/mood_track_point.dart';
import 'image_viewer.dart';

class AddMarkedPointDialog extends StatefulWidget {
  final MoodTrackPoint moodTrackPoint;
  final MoodTrack moodTrack;

  const AddMarkedPointDialog({
    super.key,
    required this.moodTrackPoint,
    required this.moodTrack
  });

  @override
  State<AddMarkedPointDialog> createState() => _AddMarkedPointDialogState();
}

class _AddMarkedPointDialogState extends State<AddMarkedPointDialog> {
  List<MoodWidget> moods = MoodWidget.list;
  MoodWidget? selectedMood;
  final TextEditingController _noteController = TextEditingController();
  final List<File> _images = [];
  final ImagePicker _picker = ImagePicker();
  late final MoodTrackAPI moodTrackAPI = MoodTrackAPI();


  @override
  void initState() {
    super.initState();
  }

  Future<void> _pickImage(ImageSource source) async {
    final XFile? image = await _picker.pickImage(source: source);
    if (image != null) {
      setState(() {
        _images.add(File(image.path));
      });
    }
  }

  void _removeImage(int index) {
    setState(() {
      _images.removeAt(index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加标记点'),
      content: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('名称：${widget.moodTrackPoint.locationName}'),
            // Text('经纬度：${widget.moodTrackPoint.latitude}, ${widget.moodTrackPoint.longitude}'),
            Text('时间：${widget.moodTrackPoint.createdAt?.toLocal().toString().substring(0, 19)}'),
            Text('天气：${widget.moodTrackPoint.weather}'),
            Text('温度：${widget.moodTrackPoint.temperature}'),
            const SizedBox(height: 8),

            DropdownButtonFormField<MoodWidget>(
              decoration: const InputDecoration(labelText: '选择心情'),
              value: selectedMood,
              items: moods.map((e) {
                return DropdownMenuItem<MoodWidget>(
                  child: SizedBox(
                    width: 30,
                    height: 30,
                    child: e.lottie,
                  ),
                  value: e,
                );
              }).toList(),
              onChanged: (value) => setState(() => selectedMood = value),
            ),

            const SizedBox(height: 8),
            TextField(
              controller: _noteController,
              decoration: const InputDecoration(
                labelText: '描述内容',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),

            const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            for (int i = 0; i < _images.length; i++)
              Stack(
                children: [
                  GestureDetector(
                    onTap: () => _showImageViewer(i),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: Image.file(
                        _images[i],
                        width: 80,
                        height: 80,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                  Positioned(
                    top: -8,
                    right: -8,
                    child: IconButton(
                      icon: const Icon(Icons.cancel, color: Colors.redAccent, size: 20),
                      onPressed: () => _removeImage(i),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                    ),
                  ),
                ],
              ),

            // 添加按钮：拍照
            GestureDetector(
              onTap: () => _pickImage(ImageSource.camera),
              child: Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.camera_alt, size: 28, color: Colors.grey),
              ),
            ),

            // 添加按钮：相册
            GestureDetector(
              onTap: () => _pickImage(ImageSource.gallery),
              child: Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.photo, size: 28, color: Colors.grey),
              ),
            ),
          ],
        )
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            if(_noteController.text.isEmpty) {
              return ;
            }
            if(selectedMood == null) {
              return ;
            }
            widget.moodTrackPoint.description = _noteController.text;
            MoodType moodType = Store.moodTypes().firstWhere((e) => e.name == selectedMood!.name);
            widget.moodTrackPoint.moodTypeId = moodType.id;
            widget.moodTrackPoint.moodLevel = 0;
            _addPoint(widget.moodTrackPoint);
            // Navigator.of(context).pop(null);
          },
          child: const Text('保存'),
        ),
      ],
    );
  }

  void _showImageViewer(int initialIndex) {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.black87,
          insetPadding: const EdgeInsets.all(16),
          child: ImageViewer(images: _images, initialIndex: initialIndex),
        );
      },
    );
  }

  void _addPoint(MoodTrackPoint point) async {
     MoodTrackPoint? currentPoint = await moodTrackAPI.addPoint(widget.moodTrack.id!, point);
    if(currentPoint == null) {
     return notify('添加失败!', context);
    }

    if(_images.isNotEmpty) {
      var values = await uploadImages(_images, currentPoint);
      Store.addPointImages(currentPoint, values);
    }
     Store.addMoodTrackPoint(currentPoint);

    Navigator.of(context).pop(currentPoint);
  }
}


